package com.toplabs.unashu.service.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.toplabs.unashu.common.response.ResponseStatus;
import com.toplabs.unashu.common.utils.JWTUtils;
import com.toplabs.unashu.entity.User;
import com.toplabs.unashu.exception.ServiceException;
import com.toplabs.unashu.mapper.UserMapper;
import com.toplabs.unashu.service.UserService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ityanger
 * @since 2020-08-23
 */
@Service
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;

    private final StringRedisTemplate stringRedisTemplate;

    public UserServiceImpl(UserMapper userMapper, StringRedisTemplate stringRedisTemplate) {
        this.userMapper = userMapper;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public JSONObject checkUser(String username, String password) throws ServiceException {
        User user = userMapper.queryUserByName(username);
        if (user == null || !password.equals(user.getPassword())) {
            throw new ServiceException(ResponseStatus.UNAUTHORIZED);
        }
        String token = JWTUtils.sign(username, password);
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("token", token);
        jsonObject.set("user", user);
        return jsonObject;
    }

    @Override
    public User queryUserByName(String username) {
        String s = stringRedisTemplate.opsForValue().get("User:username:" + username);
        if (StringUtils.hasText(s)) {
            return JSONUtil.toBean(s, User.class);
        }
        User user = userMapper.queryUserByName(username);
        stringRedisTemplate.opsForValue().set("User:username:" + username, JSONUtil.toJsonStr(user));
        return user;
    }
}
